package demo07

/**
 * @author xiaoZhao
 * @date 2022/7/26
 * @describe 测试偏函数
 */
object Test06_PartialFunction {
  def main(args: Array[String]): Unit = {
    val list = List(("a,", 12), ("b", 34), ("c", 45))

    // map转换 key不变 value两倍
    val newList = list.map(tuple => (tuple._1, tuple._2 * 2))

    // 模式匹配 对元素元素赋值
    val newList2 = list.map(
      tuple => {
        tuple match {
          case (word, count) => (word, count * 2)
        }
      }
    )

    // 省略lambda表达式 表示偏函数
    val newList3 = list.map {
      case (word, count) => (word, count * 2)
    }

    // 函数应用 求绝对值
    //
    val positiveAbs: PartialFunction[Int, Int] = {
      case x if x >= 0 => x
    }

    val pnegativeAbs: PartialFunction[Int, Int] = {
      case x if x < 0 => -x
    }

    def abs(x: Int): Int= (positiveAbs orElse pnegativeAbs)(x)

    println(abs(21))
  }
}
